package com.bw.module_cinema.model.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.bw.lib_common.base.BaseViewModel
import com.bw.module_cinema.intent.CinemaIntent
import com.bw.module_cinema.model.repository.CinemaRepository
import com.bw.module_cinema.model.state.CinemaState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CinemaViewModel @Inject constructor(private val repository: CinemaRepository) :BaseViewModel<CinemaIntent>(){

    private var typeStateFlow  = MutableStateFlow<CinemaState>(CinemaState.Init)
    val typeStateFlow_ = typeStateFlow.asStateFlow()

    // 新列表数据流（新增）
    private val newTypeStateFlow = MutableStateFlow<CinemaState>(CinemaState.Init)
    val newTypeStateFlow_ = newTypeStateFlow.asStateFlow()

    private val videoStateFlow = MutableStateFlow<CinemaState>(CinemaState.Init)
    val videoStateFlow_ = videoStateFlow.asStateFlow()

    /**
     * 1.根据不同的意图处理不同数据请求
     */
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is CinemaIntent.getMutilType -> {//请求视频类型
                        getMutilType()
                    }
                    is CinemaIntent.getMutilTypeByPid ->{
                        getCinemaTypeByPid(it.pid)
                    }
                    is CinemaIntent.getVideoByTypeId ->{
                        Log.d("CinemaViewModel", "处理getMutilTypeByPid，pid=${it.typeid}")
                        getVideoByTypeId(it.page,it.pagesize,it.typeid)
                    }
                }
            }
        }
    }

    /**
     * 2.请求的结果更新state
     */
    fun getMutilType(){
        viewModelScope.launch {
            repository.getCinemaType()
                .catch { e ->
                    typeStateFlow.value = CinemaState.Error(e.message.toString())
                }.filter {
                    it != null
                }.collect{
                    if (it.code == 200){
                        if (it.data.isNotEmpty()){
                            typeStateFlow.value = CinemaState.Success(it.data)
                        }else{
                            typeStateFlow.value = CinemaState.Empty
                        }
                    }else{
                        typeStateFlow.value = CinemaState.Error(it.msg)
                    }
                }
        }
    }

    fun getCinemaTypeByPid(pid: Int){
        viewModelScope.launch {
            repository.getCinemaTypeByPid(pid)
                .catch { e ->
                    newTypeStateFlow.value = CinemaState.Error(e.message.toString())
                }.filter {
                    it != null
                }.collect{
                    if (it.code == 200){
                        if (it.data.isNotEmpty()){
                            newTypeStateFlow.value = CinemaState.Success(it.data)
                        }else{
                            newTypeStateFlow.value = CinemaState.Empty
                        }
                    }else{
                        newTypeStateFlow.value = CinemaState.Error(it.msg)
                    }
                }
        }
    }

    fun getVideoByTypeId(page: Int, pagesize: Int, typeid: Int){
        viewModelScope.launch {
            repository.getVideoByTypeId(page, pagesize, typeid)
                .catch { e ->
                    videoStateFlow.value = CinemaState.Error(e.message.toString())
                }.filter {
                    it != null
                }.collect{
                    if (it.code == 200){
                        if (it.data.isNotEmpty()){
                            videoStateFlow.value = CinemaState.VideoSuccess(it.data)
                        }else{
                            videoStateFlow.value = CinemaState.Empty
                        }
                    }else{
                        videoStateFlow.value = CinemaState.Error(it.msg)
                    }
                }
        }
    }

    /**
     * 取消收藏视频
     */
    fun cancelCollect(videoEntity: com.bw.module_cinema.model.entity.VideoByTypeIdEntity) {
        viewModelScope.launch {
            try {
                val starEntity = com.bw.lib_storage.db.entity.VideoStarEntity(
                    id = videoEntity.id,
                    title = videoEntity.title,
                    toutiaolvideotext = videoEntity.toutiaolvideotext,
                    videomainimag = videoEntity.videomainimag
                )
                repository.cancelCollect(starEntity)
            } catch (e: Exception) {
                Log.e("CinemaViewModel", "取消收藏失败: ${e.message}")
            }
        }
    }

}